<template>
  <div class="home-box">
    <!-- 顶部卡片 -->
    <el-card>
      <div class="card-head">
        <div class="card-title">能源统计</div>
        <div class="card-option">
          <el-segmented v-model="statValue" :options="dateOption" @change="commEvent.getEnergyStat" />
        </div>
      </div>
      <el-row :gutter="20" class="mt-10">
        <el-col :span="8" v-for="item in statData" :key="item.key">
          <el-card>
            <div class="home-head">
              <el-image :src="item.cover" class="head-img" />
              <div class="head-info">
                <div class="info-title">{{ item.title }}{{ item.unit ? `（${item.unit}）` : "" }}</div>
                <div class="info-num">{{ item.value.toFixed(2) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 图表数据 -->
      <el-row :gutter="10" class="mt-20">
        <el-col :span="12">
          <el-card>
            <div class="card-title">电能趋势</div>
            <div v-if="electrics.length" class="home-cahrts">
              <e-charts :option="electricOption" />
            </div>
            <div v-else class="home-cahrts"><el-empty /></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="card-title">水燃趋势</div>
            <div v-if="waterGases.length" class="home-cahrts">
              <e-charts :option="waterGasOption" />
            </div>
            <div v-else class="home-cahrts"><el-empty /></div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mt-10">
        <el-col :span="12">
          <el-card>
            <div class="card-head">
              <div class="card-title">厂区电能排名</div>
              <div class="card-option">
                <el-select
                  v-model="factoryId"
                  placeholder="请选择厂区"
                  style="width: 120px"
                  filterable
                  @change="commEvent.getLineElectrics"
                >
                  <el-option v-for="item in factorys" :key="item.id" :label="item.organName" :value="item.id" />
                </el-select>
                <el-segmented v-model="lineElectricValue" :options="dateOption" @change="commEvent.getLineElectrics" />
              </div>
            </div>
            <div v-if="lineElectrics.length" class="home-cahrts">
              <e-charts :option="lineElectricOption" />
            </div>
            <div v-else class="home-cahrts"><el-empty /></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="card-head">
              <div class="card-title">峰平谷占比</div>
              <div class="card-option">
                <el-segmented v-model="bandvalue" :options="dateOption" @change="commEvent.getBandStats" />
              </div>
            </div>
            <div class="home-cahrts">
              <e-charts :option="bandStatOption" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import { ECOption } from "@/components/ECharts/config"
import ECharts from "@/components/ECharts/index.vue"
import {
  dateOption,
  dateValue,
  energyStatItem,
  waterGasChart,
  electricChart,
  lineElectricChart,
  bandItem,
  bandStatChart
} from "./enum"
import { energyStat, waterGasTrend, electricTrendStat, electricLineRank, bandStat } from "@/api/modules/home"
import { SystemSpace } from "@/api/interface/home"
import { organByLevel } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
// 参数
const statValue = ref<string>("day") // 能源统计日期
const statData = ref<any[]>(energyStatItem) // 能源统计数据
// 电能趋势
const electrics = ref<SystemSpace.ElectricTrendStat[]>([])
const electricOption = computed<ECOption>(() => {
  let _series: any = {}
  if (electricChart?.series && Array.isArray(electricChart?.series)) {
    _series = electricChart?.series[0]
  }
  return {
    ...electricChart,
    xAxis: { ...electricChart.xAxis, data: electrics.value.map(item => item.time) },
    series: [{ ..._series, data: electrics.value.map(item => item.value) }]
  }
})
// 水燃趋势
const waterGases = ref<SystemSpace.WaterGasTrend[]>([])
const waterGasOption = computed<ECOption>(() => {
  let _gasSeries: any = {}
  let _waterSeries: any = {}
  if (waterGasChart?.series && Array.isArray(waterGasChart?.series)) {
    _gasSeries = waterGasChart?.series[0]
    _waterSeries = waterGasChart?.series[1]
  }
  return {
    ...waterGasChart,
    xAxis: { ...waterGasChart.xAxis, data: waterGases.value.map(item => item.time) },
    series: [
      { ..._gasSeries, data: waterGases.value.map(item => item.gasValue) },
      { ..._waterSeries, data: waterGases.value.map(item => item.waterValue) }
    ]
  }
})
// 厂区电能排名
const factoryId = ref<number | undefined>(undefined) // 厂区
const factorys = ref<SystemApi.OrganByLevel[]>([]) // 厂区信息
const lineElectricValue = ref<string>("day") // 厂区电能排名日期
const lineElectrics = ref<SystemSpace.ElectricLineRank[]>([]) // 产线电能
const lineElectricOption = computed<ECOption>(() => {
  let _series: any = {}
  if (lineElectricChart?.series && Array.isArray(lineElectricChart?.series)) {
    _series = lineElectricChart?.series[0]
  }
  return {
    ...lineElectricChart,
    yAxis: { ...lineElectricChart.yAxis, data: lineElectrics.value.map(item => item.lineName) },
    series: [{ ..._series, data: lineElectrics.value.map(item => item.value) }]
  }
})
// 峰平谷占比
const bandvalue = ref<string>("day") // // 峰平谷占比日期
const bandStats = ref<any[]>(bandItem)
const bandStatOption = computed<ECOption>(() => {
  let _series: any = {}
  if (bandStatChart?.series && Array.isArray(bandStatChart?.series)) {
    _series = bandStatChart?.series[0]
  }
  let _legend: any = {}
  if (bandStatChart?.legend) {
    _legend = bandStatChart.legend
  }
  const _sum = bandStats.value.map(item => item.value).reduce((prev: number, next: number) => prev + next, 0)
  return {
    ...bandStatChart,
    legend: {
      ..._legend,
      formatter: (name: string) => {
        const _num: number = bandStats.value.find(item => item.label === name)?.value || 0
        const _unit: string = bandStats.value.find(item => item.label === name)?.unit || "kWh"
        const ratio: string = `${((_sum <= 0 ? 0 : _num / _sum) * 100).toFixed(2)}%`
        return `${name}(${_unit}) ${_num.toFixed(2)} ${ratio}`
      }
    },
    series: [{ ..._series, data: bandStats.value.map(item => ({ name: item.label, value: item.value })) }]
  }
})
// 事件
const commEvent = {
  // 获取能源统计
  getEnergyStat: async () => {
    const params = dateValue[statValue.value]
    const { data } = await energyStat(params)
    statData.value.forEach(item => {
      const _obj = data.find(val => val.energyType === item.key)
      if (_obj) {
        item.unit = _obj.unit
        item.value = _obj.value
      } else {
        item.unit = ""
        item.value = 0
      }
    })
  },
  // 获取电能趋势
  getElectric: async () => {
    const { data } = await electricTrendStat()
    electrics.value = data.map(item => ({
      time: item.time.substring(item.time.length - 2) + "时",
      value: item.value || 0
    }))
  },
  // 获取水燃趋势信息
  getWaterGas: async () => {
    const { data } = await waterGasTrend()
    waterGases.value = data.map(item => ({
      waterValue: item.waterValue || 0,
      gasValue: item.gasValue || 0,
      time: item.time.substring(item.time.length - 2) + "时"
    }))
  },
  // 获取厂区数据信息
  getFactorys: async () => {
    const { data } = await organByLevel(1)
    factorys.value = data
    if (data && data.length) {
      factoryId.value = data[0].id
      commEvent.getLineElectrics()
    }
  },
  // 获取产线电能排名
  getLineElectrics: async () => {
    const params: SystemSpace.ElectricLineRankQuery = {
      ...dateValue[lineElectricValue.value],
      factoryId: Number(factoryId.value)
    }
    const { data } = await electricLineRank(params)
    lineElectrics.value = data.map(item => ({
      ...item,
      value: item.value || 0
    }))
  },
  // 获取峰平谷占比数据
  getBandStats: async () => {
    const params = dateValue[bandvalue.value]
    const { data } = await bandStat(params)
    const _obj: any = data
    bandStats.value.forEach(item => {
      item.value = _obj[item.key]
      item.unit = _obj.unit
    })
  }
}
onMounted(() => {
  commEvent.getEnergyStat()
  commEvent.getElectric()
  commEvent.getWaterGas()
  commEvent.getFactorys()
  commEvent.getBandStats()
})
</script>

<style lang="scss" scoped>
.home-box {
  width: 100%;
  .mt-10 {
    margin-top: 10px;
  }
  .mt-20 {
    margin-top: 20px;
  }
  .home-head {
    display: flex;
    gap: 10px;
    align-items: center;
    .head-img {
      width: 80px;
      height: 80px;
      border-radius: 50%;
    }
    .head-info {
      flex: 1;
      .info-title {
        margin-bottom: 5px;
        font-size: 16px;
      }
      .info-num {
        font-size: 24px;
      }
    }
  }
  .card-head {
    display: flex;
    align-items: center;
    .card-option {
      display: flex;
      flex: 1;
      gap: 20px;
      justify-content: flex-end;
    }
  }
  .card-title {
    width: 100%;
    font-size: 16px;
    font-weight: bold;
  }
  .home-cahrts {
    width: 100%;
    height: 300px;
  }
}
</style>
